package com.zhouyer.study.filter;

import com.zhouyer.study.feign.UserFeignClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

/**
 * 登录全局过滤器
 *
 * @author zhouyao
 * @version 1.0
 * @date 2021/12/7 10:01 下午
 */
@Component
@Slf4j
public class ValidateTokenFilter implements GlobalFilter, Ordered {
    @Resource
    private UserFeignClient userFeignClient;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1、从上下文获取request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 获取访问地址
        String url = request.getPath().toString();
        // ⽤户微服务和验证码微服务的请求不过滤（⽹关调⽤下游⽤户微服务的token验证接⼝）
        String codeUrlPrefix = "/api/code";
        String userUrlPrefix = "/api/user";
        if (url.contains(codeUrlPrefix) || url.contains(userUrlPrefix)) {
            return chain.filter(exchange);
        }
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        boolean tokenExist = cookies.containsKey("token");
        if (tokenExist) {
            String token = cookies.getFirst("token").getValue();
            if (StringUtils.isNotBlank(token)) {
                // 验证token
                String email = userFeignClient.userEmailInfo(token);
                if (StringUtils.isNotBlank(email)) {
                    // 合法的token，放行，执行后面的过滤器
                    return chain.filter(exchange);
                }
            }
        }
        log.info("token不存在，请求不合法");
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        // 重定向到登录页面
        response.getHeaders().add("Location", "/static/login.html");
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
